package com.health.utils;

import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class WebContextUtil {
    private static WebApplicationContext wac;

    public static HttpServletRequest getCurrentRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request;
    }

    public static WebApplicationContext getWebApplicationContext() {
        if (wac == null) {
            HttpServletRequest request = getCurrentRequest();
            wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
        }
        return wac;
    }

    public static WebApplicationContext getWebApplicationContext(ServletContextEvent event) {
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext());
        return wac;
    }

    /**
     * 根据bean名称获取bean
     * 
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return getWebApplicationContext().getBean(beanName);
    }

    public static WebApplicationContext getWac() {
        return wac;
    }

    public static void setWac(WebApplicationContext wac) {
        WebContextUtil.wac = wac;
    }
}
